# encoding: utf-8

#from django.contrib import admin
import xadmin
from xadmin import views
from django.core import urlresolvers
from .models import *
from xadmin.layout import Main, TabHolder, Tab, Fieldset, Row, Col, AppendedText, Side
from xadmin.plugins.inline import Inline
from xadmin.plugins.batch import BatchChangeAction
from xadmin.models import UserWidget,UserSettings
from django.contrib.auth.models import User,Permission,Group
#import sms_ChinaMobile
from django.conf import settings
import xadmin.plugins.auth

import logging
logger = logging.getLogger(__name__)


from django.contrib.auth.models import User,Permission


class DepartmentAdmin(object):
    list_display=('department_name',)
    #list_filter=('department_type',)
    search_fields = ('department_name',)
    model_icon = 'fa fa-sitemap'
    #def queryset(self):
    #    qs = super(DepartmentAdmin, self).queryset()
        #print self.user
    #    if self.user.is_superuser:  
    #        return qs  
    #    return qs.filter(id=Users.objects.get(id=UserExtension.objects.get(userextension_authuser_id = self.user.id).userextension_users_id).user_department_id)

class YudingPermissionAdmin(object):
    pass

#------------------------------
class UsersTypeAdmin(object):
    """
    用户类型
    """
    list_display=('name','permission','brief' )
    model_icon = 'fa fa-cogs'
    style_fields = {'permission': 'm2m_transfer'}

    def save_models(self):
        obj = self.new_obj
        glist=Group.objects.filter(name=obj.name)
        if len(glist)==0:
            Group.objects.create(name=obj.name)

        obj.save()

    def delete_models(self, queryset):
        #logger.info('------ delete_models--------')
        #self.message_user('ddddd329083084','success')
        for obj in queryset:
            if (obj.name==u'预约用户组') | (obj.name==u'审批用户组'):
                self.message_user(obj.name+' 系统禁止删除','success')
                return 
            Group.objects.filter(name=obj.name).exclude(name=u'预约用户组').exclude(name=u'审批用户组').delete()

        super(UsersTypeAdmin, self).delete_models(queryset)



#------------------------
#参数定义，以备用户定义使用
html_w={"type": "html", 'value':'{"type": "html", "title": "小提示", "content": "<h3> 您好欢迎使用会议室预约系统! </h3><p>预约会议室，您可以点击左侧的<预订会议室> <br/></p>"}'}
room_w={"type": "roomlist", 'value':'{"params": {"o": "-create_time"}, "model": "yudingapp.yulan_Room", "type": "roomlist"}'}     
#-----------------------
class UsersAdmin(object):
    """
    用户管理
    """
    list_display=('user','user_name','user_type','user_department','user_mobilephone',)
    search_fields=('user_name','user_mobilephone','user_employeeid' )
    list_filter=('user_type','user_department', )
    style_fields = {'user_type': 'm2m_transfer'}
    #model_icon = 'fa fa-user-plus'


    def save_models(self):
        obj = self.new_obj
        logger.info('------kxs save_models--------'+str(obj.id))
        """
        创建用户的同时生成auth中用户的信息
        """
        if obj.id  is None:
            #第一次时
            obj.user.is_active=True
            obj.user.is_staff=True
            obj.save()
            #根据user_type判断用户组别
            
            for item in obj.user_type.all():
                glist=Group.objects.filter(name=item.name)
                if len(glist)>0:
                    obj.user.groups.add(glist[0])


            roomlistarray=UserWidget.objects.filter(user_id=obj.user_id,widget_type='roomlist')
            if len(roomlistarray) ==0:
                #创建widget，以后是否能够给予分组创建widget能
                w1=UserWidget.objects.create(user=obj.user,widget_type=html_w['type'],value=html_w['value'],page_id='home')
                w2=UserWidget.objects.create(user=obj.user,widget_type=room_w['type'],value=room_w['value'],page_id='home')            
                UserSettings.objects.create(user=obj.user,key='dashboard:home:pos',value=str(w1.id)+','+str(w2.id))
            
            obj.user.save()
            obj.save()
        
        else:
            super(UsersAdmin, self).save_models() 


    def save_related(self):
        obj = self.new_obj
        super(UsersAdmin, self).save_related()  
        obj.user.groups.clear()
        for item in obj.user_type.all():
            glist=Group.objects.filter(name=item.name)
            if len(glist)>0:
                obj.user.groups.add(glist[0])

        obj.user.save()
        obj.save()



    def delete_models(self, queryset):
        #logger.info('------ delete_models--------')
        #self.message_user('ddddd329083084','success')
        for obj in queryset:
            UserWidget.objects.filter(user=obj.user).delete()
            UserSettings.objects.filter(user=obj.user).delete()
            obj.user.delete()

        super(UsersAdmin, self).delete_models(queryset)


              


xadmin.site.register(YudingPermission,YudingPermissionAdmin)
xadmin.site.register(Department,DepartmentAdmin)
xadmin.site.register(UsersType,UsersTypeAdmin)
xadmin.site.register(Users,UsersAdmin)
#xadmin.site.register(Groups,GroupsAdmin)
#xadmin.site.register(UsersGroup,UsersGroupAdmin)
